package com.enhe.gck.pojo;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import com.enhe.gck.communal.PublicConstant;
import com.enhe.gck.item.OrderHWANE16677Item;
import com.enhe.gck.item.PouringOrderHWANE18490Item;
import com.enhe.gck.item.SupplyOrderHWANE16829Item;
import com.enhe.gck.utils.DateUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.enhe.gck.CarbonBaseConstant.*;
import static com.enhe.gck.CarbonEnumKeyValue.*;

/**
 * 订单
 */
@Data
public class OrderCommon {

    /**
     * 唯一编码
     */
    private Long id;
    /**
     * 单号
     */
    private String order;
    /**
     * 销售金额
     */
    private BigDecimal salesAmount;
    /**
     * 8位取货码
     */
    private String pickupCode;
    /**
     * 类型
     */
    private String type;
    /**
     * 包装类型(只有销售订单有)
     */
    private String packTypeZH;
    private String packTypeEN;
    /**
     * 倒料订单类型(场内转运or矿山原料拉运)
     */
    private String pouringOrderTypeZH;
    private String pouringOrderTypeEN;
    /**
     * 重量
     */
    private BigDecimal weight;
    /**
     * 袋装数
     */
    private Integer bags;
    /**
     * 单袋重量
     */
    private BigDecimal singleWeight;
    /**
     * 收货类型
     */
    private String collectType;
    private String collectTypeStr;
    /**
     * 是否作废
     */
    private String isCancel;
    /**
     * 是否退货
     */
    private String isRefund;
    /**
     * 状态
     */
    private String state;
    private String stateStr;
    /**
     * IC卡号
     */
    private String icCard;
    /**
     * 实际重量
     */
    private BigDecimal actualWeight;
    /**
     * 运费
     */
    private BigDecimal fare;
    /**
     * 是否按吨计运费
     */
    private String isTon;
    /**
     * 是否散户下单
     */
    private String isRetail;
    /**
     * 是否同步
     */
    private Boolean isSync;
    /**
     * 是否扣重
     */
    private Boolean isWeightDeduction;
    /**
     * 订单来源
     */
    private String orderSource;
    /**
     * 是否已开票
     */
    private Boolean invoicedFlag;
    /**
     * 是否已打印小票
     */
    private Boolean receiptPrintedFlag;
    /**
     * 小票打印次数
     */
    private Integer receiptPrintedNumber;
    /**
     * 实际袋装数
     */
    private Integer actualBags;
    /**
     * 补包数
     */
    private Integer supplementBags;
    /**
     * 上次装货量
     */
    private Integer lastLoadingVolume;
    /**
     * 装车完成标记
     */
    private Boolean isLoadComplete;


    /**
     * 订单类型
     */
    private String orderTypeEn;
    private String orderTypeZh;
    /**
     * 供应商名称 or 发货单位 or 客户名称
     */
    private String companyName;
    /**
     * 客户类型
     */
    private String customerType;
    /**
     * 运输商名称
     */
    private String transporterName;
    /**
     * 物料id
     */
    private Long materialId;
    /**
     * 物料名称
     */
    private String materialName;
    /**
     * 公司
     */
    private String corp;
    /**
     * 驾驶员
     */
    private String driver;
    /**
     * 车号
     */
    private String vehicle;
    /**
     * 车辆类型【101.销售车辆，102.材料车辆，105行政车辆】
     */
    private String vehicleType;
    private String vehicleTypeName;
    /**
     * 车型类型
     */
    private String vehicleStructureTypeStr;
    /**
     * [倒料订单]车辆皮重
     */
    private BigDecimal weightTare;
    /**
     * [倒料订单]车辆皮重下限
     */
    private BigDecimal weightTareDown;
    /**
     * [倒料订单]车辆皮重上限
     */
    private BigDecimal weightTareUp;
    /**
     * [倒料订单]车辆最新皮重
     */
    private BigDecimal weightTareNew;
    /**
     * [倒料订单]车辆最新皮重更新时间
     */
    private LocalDateTime weightTareNewTime;
    /**
     * 订单创建时间字符串
     */
    private String orderCreateTimeStr;

    /**
     * 是否检查红外
     */
    private Boolean infraredCheck;
    /**
     * 是否验收
     */
    private Boolean isCheck;
    /**
     * 是否化验室化验
     */
    private Boolean isTest;
    /**
     * 进厂日期字符串
     */
    private String inTime;
    /**
     * 出厂日期字符串
     */
    private String outTime;
    /**
     * 皮重
     */
    private BigDecimal tareWeight;
    /**
     * 毛重
     */
    private BigDecimal grossWeight;
    /**
     * 净重
     */
    private BigDecimal netWeight;
    /**
     * 过磅净重千克大写
     */
    private String netWeightUpperCaseKg;
    /**
     * 订单表key
     */
    private String orderTableKey;
    /**
     * 订单状态key
     */
    private String orderStateKey;
    /**
     * 订单上次装货量key
     */
    private String lastLoadingVolumeKey;
    /**
     * 订单装车完成key
     */
    private String orderLoadCompleteKey;
    /**
     * 充值单号
     */
    private String rechargeNumber;
    /**
     * 客商可下单重量
     */
    private Double weightUsable;
    /**
     * 客商可下单袋数
     */
    private String bagUsable;
    /**
     * 批次类型
     */
    private String batchType;
    // 批次名称
    private String batchNumberNames;
    // 原材料产地
    private String materialPlace;

    @JsonIgnore
    private Long customerId;

    /**
     * 异常时是否通过
     */
    private Boolean exceptionPassOrNot;

    /**
     * order转orderCommon
     *
     * @param order order
     * @return orderCommon
     */
    public static OrderCommon convertOrder(Order order) {
        OrderCommon common = new OrderCommon();
        common.setId(order.getId());
        common.setOrder(order.getOrder());
        common.setSalesAmount(null == order.getSalesAmount() ? null : BigDecimal.valueOf(order.getSalesAmount()));
        common.setPickupCode(order.getPickupCode());
        common.setType(order.getType());
        common.setPackTypeZH(getPackTypeValue(order.getType(), true));
        common.setPackTypeEN(getPackTypeValue(order.getType(), false));
        common.setWeight(null == order.getWeight() ? null : BigDecimal.valueOf(order.getWeight()));
        // 设置净重
        common.setNetWeight(null == order.getActualWeight() ? null : BigDecimal.valueOf(order.getActualWeight()).setScale(2, RoundingMode.HALF_UP));
        common.setBags(order.getBags());
        common.setSingleWeight(null == order.getSingleWeight() ? null : BigDecimal.valueOf(order.getSingleWeight()));
        common.setCollectType(order.getCollectType());
        common.setCollectTypeStr(getCollectTypeValue(order.getCollectType()));
        common.setIsCancel(order.getIsCancel());
        common.setIsRefund(order.getIsRefund());
        common.setState(order.getState());
        common.setStateStr(getStateValue(order.getState()));
        common.setIcCard(order.getIcCard());
        common.setActualWeight(null == order.getActualWeight() ? null : BigDecimal.valueOf(order.getActualWeight()));
        common.setFare(null == order.getFare() ? null : BigDecimal.valueOf(order.getFare()));
        common.setIsRetail(order.getIsRetail());
        common.setIsSync(order.isSync());
        common.setOrderSource(order.getOrderSource());
        common.setInvoicedFlag(order.getInvoicedFlag());
        common.setReceiptPrintedFlag(order.getReceiptPrintedFlag());
        common.setReceiptPrintedNumber(order.getReceiptPrintedNumber());
        common.setActualBags(order.getActualBags());
        common.setSupplementBags(order.getSupplementBags());
        common.setLastLoadingVolume(order.getLastLoadingVolume());
        common.setIsLoadComplete(order.getIsLoadComplete());
        common.setExceptionPassOrNot(order.getExceptionPassOrNot());

        common.setOrderTypeEn(PublicConstant.OrderTypeSale);
        common.setOrderTypeZh(PublicConstant.OrderTypeSaleZH);
        common.setInTime(null == order.getCardIssuanceTime() ? null : order.getCardIssuanceTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        common.setOutTime(null == order.getCardCollectionTime() ? null : order.getCardCollectionTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));

        if (String.valueOf(是否_是_s).equals(order.getIsRetail())) {
            Customer customer = order.getCustomerS();
            if (!Objects.isNull(customer)) {
                common.setCustomerId(customer.getId());
                common.setCompanyName(customer.getName());
                common.setCustomerType(customer.getType());
            }
        } else {
            Customer customer = order.getCustomer();
            if (!Objects.isNull(customer)) {
                common.setCustomerId(customer.getId());
                common.setCompanyName(customer.getName());
                common.setCustomerType(customer.getType());
            }
        }

        Goods goods = order.getGoods();
        if (!Objects.isNull(goods)) {
            common.setMaterialId(goods.getId());
            common.setMaterialName(goods.getName());
            common.setBatchType(goods.getBatchType());
        }
        Car car = order.getCar();
        if (!Objects.isNull(car)) {
            common.setVehicle(car.getCarNo());
            common.setInfraredCheck(car.isInfraredCheck());
            common.setVehicleStructureTypeStr(Objects.equals(车辆管理_车型类型_平板货车_pbhc, Long.valueOf(car.getVehicleStructureType())) ? "平板货车" : "厢式货车");
        }
        Driver orderDriver = order.getDriver();
        if (!Objects.isNull(orderDriver)) {
            common.setDriver(orderDriver.getXm姓名());
        }
//        common.setVehicleType("101");
        common.setVehicleTypeName("销售车辆");
        common.setOrderTableKey(订单记录_ddjl);
        common.setOrderStateKey(OrderHWANE16677Item.基本属性组_状态);
        common.setLastLoadingVolumeKey(OrderHWANE16677Item.基本属性组_上次装货量);
        common.setOrderLoadCompleteKey(OrderHWANE16677Item.基本属性组_装车完成标记);
        // 设置充值单号
        if (Objects.nonNull(order.getDeductions()) && CollectionUtil.isNotEmpty(order.getDeductions())) {
            Optional<List<String>> rechargeOrderListOptional = Optional.of(order.getDeductions().stream().map(Deduction::getRecharge).filter(Objects::nonNull).map(Recharge::getOrder).collect(Collectors.toList()));
            rechargeOrderListOptional.ifPresent(strings -> common.setRechargeNumber(String.join(",", strings)));
        }
        if (CollectionUtil.isNotEmpty(order.getLoadingBatchRecords())) {
            common.setBatchNumberNames(order.getLoadingBatchRecords().stream().map(LoadingBatchRecord::getBatchNumber).collect(Collectors.joining(",")));
        }
        return common;
    }

    /**
     * 获取订单状态
     *
     * @param state 状态
     * @return 状态
     */
    public static String getStateValue(String state) {
        long stateLong = Long.parseLong(state);
        if (Objects.equals(订单记录_状态_已创建_ycj, stateLong)) {
            return PublicConstant.OrderStateCreated;
        }
        if (Objects.equals(订单记录_状态_待过一磅_dgyb, stateLong)) {
            return PublicConstant.OrderStatePending;
        }
        if (Objects.equals(订单记录_状态_待装卸货_dzxh, stateLong)) {
            return PublicConstant.OrderStatePendingLoading;
        }
        if (Objects.equals(订单记录_状态_待过二磅_dgeb, stateLong)) {
            return PublicConstant.OrderStatePendingTwo;
        }
        if (Objects.equals(订单记录_状态_待归还卡_dghk, stateLong)) {
            return PublicConstant.OrderStatePendingReturn;
        }
        if (Objects.equals(订单记录_状态_已出厂_ycc, stateLong)) {
            return PublicConstant.OrderStateOutFactory;
        }
        return null;
    }

    /**
     * 收货类型
     *
     * @param collectType 收货类型
     * @return 类型字符串
     */
    private static String getCollectTypeValue(String collectType) {
        if (Objects.equals(订单信息_收货类型_自提_zt, Long.parseLong(collectType))) {
            return PublicConstant.OrderReceiptTypeSelf;
        }
        if (Objects.equals(订单信息_收货类型_配送_ps, Long.parseLong(collectType))) {
            return PublicConstant.OrderReceiptTypeTransport;
        }

        return null;
    }

    /**
     * 设置订单包装类型
     *
     * @param type 订单类型long字符串
     * @return 类型字符串
     */
    private static String getPackTypeValue(String type, boolean chineseFlag) {
        Long value = Long.valueOf(type);
        if (Objects.equals(订单记录_类型_袋装_dz, value)) {
            return chineseFlag ? PublicConstant.ProductPackageTypeBagZH : PublicConstant.ProductPackageTypeBag;
        }
        if (Objects.equals(订单记录_类型_散装_sz, value)) {
            return chineseFlag ? PublicConstant.ProductPackageTypeBulkZH : PublicConstant.ProductPackageTypeBulk;
        }
        if (Objects.equals(订单记录_类型_吨包_db, value)) {
            return chineseFlag ? PublicConstant.ProductPackageTypeTonZH : PublicConstant.ProductPackageTypeTon;
        }
        return null;
    }

    public static OrderCommon convertSupplyOrder(SupplyOrder supplyOrder) {
        OrderCommon common = new OrderCommon();
        common.setId(supplyOrder.getId());
        common.setOrder(supplyOrder.getOrder());
        common.setPickupCode(supplyOrder.getPickupCode());
        // 设置净重
        common.setNetWeight(null == supplyOrder.getActualWeight() ? null : BigDecimal.valueOf(supplyOrder.getActualWeight()).setScale(2, RoundingMode.HALF_UP));
        common.setIsCancel(supplyOrder.getIsCancel());
        common.setIsRefund(supplyOrder.getIsRefund());
        common.setState(supplyOrder.getState());
        common.setStateStr(getStateValue(supplyOrder.getState()));
        common.setIcCard(supplyOrder.getIcCard());
        common.setActualWeight(null == supplyOrder.getActualWeight() ? null : BigDecimal.valueOf(supplyOrder.getActualWeight()));
        common.setIsWeightDeduction(supplyOrder.isWeightDeduction());
        common.setOrderSource(supplyOrder.getOrderSource());
        common.setInvoicedFlag(supplyOrder.getInvoicedFlag());
        common.setReceiptPrintedFlag(supplyOrder.getReceiptPrintedFlag());
        common.setReceiptPrintedNumber(supplyOrder.getReceiptPrintedNumber());

        common.setOrderTypeEn(PublicConstant.OrderTypeSupply);
        common.setOrderTypeZh(PublicConstant.OrderTypeSupplyZH);
        common.setIsCheck(supplyOrder.isCheck());
        common.setIsTest(supplyOrder.isTest());

        common.setInTime(null == supplyOrder.getCardIssuanceTime() ? null : supplyOrder.getCardIssuanceTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
        common.setOutTime(null == supplyOrder.getCardCollectionTime() ? null : supplyOrder.getCardCollectionTime().format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));

        Customer customer = supplyOrder.getCustomer();
        if (!Objects.isNull(customer)) {
            common.setCompanyName(customer.getName());
        }
        Material material = supplyOrder.getMaterial();
        if (!Objects.isNull(material)) {
            common.setMaterialName(material.getName());
        }
        Car car = supplyOrder.getCar();
        if (!Objects.isNull(car)) {
            common.setVehicle(car.getCarNo());
            common.setInfraredCheck(car.isInfraredCheck());
        }
        Driver orderDriver = supplyOrder.getDriver();
        if (!Objects.isNull(orderDriver)) {
            common.setDriver(orderDriver.getXm姓名());
        }
        if (!Objects.isNull(supplyOrder.getTransporterCustomer())) {
            common.setTransporterName(supplyOrder.getTransporterCustomer().getName());
        }
        if (Objects.nonNull(supplyOrder.getSupplyOrderBig())) {
            common.setMaterialPlace(convertMateriaPlace(supplyOrder.getSupplyOrderBig().getMaterialPlace()));
        }
//        common.setVehicleType("102");
        common.setVehicleTypeName("材料车辆");
        common.setOrderTableKey(供货订单_ghdd);
        common.setOrderStateKey(SupplyOrderHWANE16829Item.基本属性组_状态);
//        common.setOrderCreateTimeStr(DateUtil.DateTimeToString(supplyOrder.getCreateTime()));
        // 原材料打印时间要求使用当前时间！！！（2024/9/23 改）
        common.setOrderCreateTimeStr(DateUtil.DateTimeToString(LocalDateTime.now()));
        return common;
    }

    public static String convertMateriaPlace(Long materialPlace) {
        if (Objects.equals(原材料产地_津巴布韦_jbbw, materialPlace)) {
            return "津巴布韦（Zimbabwe）";
        }
        if (Objects.equals(原材料产地_赞比亚_zby, materialPlace)) {
            return "赞比亚（Zambie）";
        }
        return null;
    }

    public static OrderCommon convertPouringOrder(PouringOrder pouringOrder) {
        OrderCommon common = new OrderCommon();
        common.setId(pouringOrder.getId());
        common.setOrder(pouringOrder.getOrder());
        common.setWeight(null == pouringOrder.getWeight() ? null : BigDecimal.valueOf(pouringOrder.getWeight()));
        common.setState(pouringOrder.getState());
        common.setStateStr(getStateValue(pouringOrder.getState()));
        common.setIcCard(pouringOrder.getIcCard());
        common.setOrderSource(pouringOrder.getOrderSource());
        common.setOrderTypeEn(PublicConstant.OrderTypePouring);
        common.setOrderTypeZh(PublicConstant.OrderTypePouringZH);
        common.setPouringOrderTypeEN(getPouringOrderType(pouringOrder.getType() , false));
        common.setPouringOrderTypeZH(getPouringOrderType(pouringOrder.getType() , true));

        Material material = pouringOrder.getMaterial();
        if (Objects.nonNull(material)) {
            common.setMaterialName(material.getName());
        }
        Car car = pouringOrder.getCar();
        if (!Objects.isNull(car)) {
            common.setVehicle(car.getCarNo());
            common.setInfraredCheck(car.isInfraredCheck());
            common.setWeightTare(car.getWeightTare());
            common.setWeightTareDown(car.getWeightTareDown());
            common.setWeightTareUp(car.getWeightTareUp());
            common.setWeightTareNew(car.getWeightTareNew());
            common.setWeightTareNewTime(car.getWeightTareNewTime());
        }
        Driver orderDriver = pouringOrder.getDriver();
        if (!Objects.isNull(orderDriver)) {
            common.setDriver(orderDriver.getXm姓名());
        }
        common.setVehicleTypeName("倒料车辆");
        common.setOrderTableKey(倒料订单_dldd);
        common.setOrderStateKey(PouringOrderHWANE18490Item.基本属性组_状态);
        return common;
    }

    private static String getPouringOrderType(String type, boolean chineseFlag) {
        Long value = Long.valueOf(type);
        if (Objects.equals(倒料类型_原料拉运_ylly, value)) {
            return chineseFlag ? PublicConstant.PouringOrderTypeMineRawMaterialTransferZH : PublicConstant.PouringOrderTypeMineRawMaterialTransfer;
        }
        if (Objects.equals(倒料类型_场内转运_cnzy, value)) {
            return chineseFlag ? PublicConstant.PouringOrderTypeOnSiteTransferZH : PublicConstant.PouringOrderTypeOnSiteTransfer;
        }
        return null;
    }
}
